package com.navercorp.utilset.system;

import java.io.File;
import java.io.FileFilter;
import java.util.regex.Pattern;

/**
 * Function description
 * class ProcessorUtils
 */
public class ProcessorUtils {
    private ProcessorUtils() {
        /* Do nothing */
    }

    /**
     * getNumCores
     * Gets the number of cores available in this device, across all processors.
     * Requires: Ability to peruse the file system at "/sys/devices/system/cpu"
     * @return The number of cores, or Runtime.getRuntime().availableProcessors() if failed to get result
     */
    public static int getNumCores() {
        /**
         * Function description
         * class CpuFilter
         */
        class CpuFilter implements FileFilter {
            @Override
            public boolean accept(File pathname) {
                return Pattern.matches("cpu[0-9]", pathname.getName());
            }
        }

        try {
            File dir = new File("/sys/devices/system/cpu/");
            File[] files = dir.listFiles(new CpuFilter());

            if (files == null) {
                return Runtime.getRuntime().availableProcessors();
            }
            return files.length;
        } catch (Exception e) {
            return Runtime.getRuntime().availableProcessors();
        }
    }
}
